package spectra.ee.web.qna.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.collections.map.CaseInsensitiveMap;

import spectra.base.log.Logger;
import spectra.base.util.DateUtil;
import spectra.base.util.StringUtil;
import spectra.ee.EEPublic;
import spectra.ee.commons.common.model.Attach;
import spectra.ee.commons.qna.model.Qna;
import spectra.ee.commons.qna.model.QnaBoard;
import spectra.ee.commons.qna.model.QnaContents;
import spectra.ee.commons.qna.model.QnaProcess;
import spectra.ee.commons.qna.model.form.QnaForm;
import spectra.ee.web.api.ApiPublic;
import spectra.ee.web.qna.model.QnaBoardView;
import spectra.ee.web.qna.model.QnaWebForm;

/**
 * Qna관련 클래스.
 *
 * @author dhheo
 */
public class QnaWebService extends QnaServiceBase
{

    /** Logger객체. */
    private static Logger logger = Logger.getLoggerInstance(QnaWebService.class.getName());
    
    /**
     * <pre>
     * 공개게시판 리스트를 가져오는 메소드
     * </pre>.
     */
    public List selectQnaList(QnaBoardView qnaBoard)
    {
    	List lstRet = null;
    	try
        {
            lstRet = (List) sqlMap.queryForList("Qna.selectQnaTopList", qnaBoard);
        }
        catch (SQLException e)
        {
            logger.error(e.getMessage());
        }
        return lstRet;
    }
    
    /**
     * <pre>
     * qna_id에 해당하는 contents를 가져오는 메소드
     * </pre>.
     *
     * @param qnaBoardView Qna아이디.
     *
     * @return CaseInsensitiveMap(qna_id에 해당하는 질/답내용 리스트)
    */
    public List selectQnaContents(QnaBoardView qnaBoardView)
    {
        List listRet = null;
        try
        {
            qnaBoardView.setReadFlag(EEPublic.FLAG_Y);
            sqlMap.update("Qna.updateReadFlagByEndPK", qnaBoardView);

            listRet = (List) sqlMap.queryForList("Qna.selectQnaContentsByQnaId", qnaBoardView);
        }
        catch (SQLException e)
        {
            logger.error(e.getMessage());
        }
        return listRet;
    }
    
    /**
     * <pre>
     * qna_id에 해당하는 질문/답변 내용을 가져오는 메소드
     * </pre>.
     *
     * @param qnaBoardView Qna아이디.
     *
     * @return CaseInsensitiveMap(qna_id에 해당하는 질/답내용 리스트)
    */
    public List selectQnaContentsList(QnaBoardView qnaBoardView)
    {
        List listRet = new ArrayList();
        try
        {
        	sqlMap.startTransaction();
        	
            qnaBoardView.setReadFlag(EEPublic.FLAG_Y);
            sqlMap.update("Qna.updateReadFlagByEndPK", qnaBoardView);	// 읽음여부 update
            sqlMap.update("Qna.updateQnaHitCount", qnaBoardView);		// 조회수 증가
            
            sqlMap.commitTransaction();
            
            List listContents = null;
            String strDomainId = "";
            String strAnswerStatus = "";
            String strApprovalStatus = "";
            String strSpamFlag = "";
            String strSpamPassId = "";
            
            // domainId, qnaId 로 질의내용을 가져온다.
        	QnaBoardView qna  = (QnaBoardView) sqlMap.queryForObject("Qna.selectQnaByQnaId", qnaBoardView);
            
        	strDomainId = qnaBoardView.getQnaDomainId();
        	strAnswerStatus = StringUtil.defaultString(qna.getAnswerStatus());
        	strApprovalStatus = StringUtil.defaultString(qna.getApprovalStatus());
            strSpamFlag = StringUtil.defaultString(qna.getSpamFlag(), "N");
            strSpamPassId = StringUtil.defaultString(qna.getSpamPassId());
            
            /*
             * qnaId로 질의 내용을 가져온다.
             * contentsType이 Q일 경우 질문 A일 경우 답변
             */
            QnaBoardView param = new QnaBoardView();
            if ("Y".equals(strSpamFlag) && strSpamPassId.length() > 0)
			{
				// 시스템 스팸룰에 걸렸을때
            	param.setQnaDomainId(strDomainId);
            	param.setQnaId(strSpamPassId);
            	
            	listContents = (List) sqlMap.queryForList("Qna.selectQnaContentsByQnaId", param);
				
				// 스팸을 통과한 대표 qna 의 답변상태와 승인상태 필드를 읽어온다.
                QnaBoardView spamQna = (QnaBoardView) sqlMap.queryForObject("Qna.selectQnaByQnaId", param);
				strAnswerStatus = StringUtil.defaultString(spamQna.getAnswerStatus());
				strApprovalStatus = StringUtil.defaultString(spamQna.getApprovalStatus());
			}
			else if ("Y".equals(strSpamFlag) && strSpamPassId.length() == 0)
			{
				// 사용자정의 스팸룰에 걸렸을때
				listContents = (List) sqlMap.queryForList("Qna.selectQnaContentsByQnaId", qnaBoardView);

				// 고정된 답변을 추가한다.				
				CaseInsensitiveMap tempMap = new CaseInsensitiveMap();
				tempMap.put("PROCESS_SEQ", 1);
				tempMap.put("TYPE", "ANEND");
				tempMap.put("CONTENTS_TYPE", "A");
				tempMap.put("TITLE", "-");
				tempMap.put("CONTENTS", "내부정책에 의해 스팸처리 되었습니다.");
				
				listContents.add(tempMap);
				
				strAnswerStatus = "ANEND";
			}
			else
			{
				listContents = (List) sqlMap.queryForList("Qna.selectQnaContentsByQnaId", qnaBoardView);
			}
            
            String strType = "";
            String strContentsType = "";
            
            if (listContents != null && listContents.size() > 0)
            {
            	CaseInsensitiveMap map = null;
                for (int i = 0; i < listContents.size(); i++)
                {
                	map = (CaseInsensitiveMap)listContents.get(i);
                	
                	strType = (String) map.get("TYPE");		// 프로세스상 답변상태(t_qna_process)
                	strContentsType = (String) map.get("CONTENTS_TYPE");
                	
                	if ("Q".equals(strContentsType))
                    {
                		listRet.add(map);
                		continue;
                    }
                	else if ("A".endsWith(strContentsType))
                	{
                		/* 답변상태가 아래의 경우에만 화면에 보여준다.
            			 * 	- 중간답변(ANTMP), 답변완료(ANEND), 추가답변(ANADD) */
                		if("ANTMP".equals(strType) || "ANEND".equals(strType) || "ANADD".equals(strType))
                		{
                			map.put("APPROVAL_STATUS", strApprovalStatus);
                			listRet.add(map);
                		}
                	}
                }
            }
        }
        catch (SQLException e)
        {
            logger.error(e.getMessage());
        }
        finally
        {
            try
            {
                sqlMap.endTransaction();
            }
            catch(SQLException e)
            {
                logger.error(e.getMessage());
            }
        }
        
        return listRet;
    }

    /**
     * 이메일상담 등록(App용)
     * @param qnaForm
     * @return
     */
    public String insertQna(QnaForm qnaForm)
    {
    	String createdDate = DateUtil.getCurrDateTimeStamp();
    	//Qna 중 파라메터로 받는 값들
    	//파라메터로 받지 않은 기본값을 셋팅한다.  
    	Qna qna = (Qna)qnaForm;
    	 
    	qna.setAccountId(StringUtil.defaultIfEmpty(qna.getAccountId(), ApiPublic.ACCOUNT_ID_NO_AGENT));
    	qna.setAnswerChannelId(StringUtil.defaultIfEmpty(qna.getAnswerChannelId(), ApiPublic.CHANNEL_ID_NOT_RESPONSE));
    	 
    	//제목이 안넘오어면 내용에서 앞 부분을 짤라서 제목으로 구성한다.
    	qna.setSpamFlag(StringUtil.defaultIfEmpty(qna.getSpamFlag(), ApiPublic.FLAG_I));
    	qna.setCreatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
    	qna.setCreatedDate(createdDate);
    	qna.setUpdatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
    	qna.setUpdatedDate(createdDate);
    	 
    	//qna board 셋팅
    	QnaBoard qnaBoard = qnaForm.getQnaBoard();
    	qnaBoard.setCreatedDate(createdDate);
    	qnaBoard.setUpdatedDate(createdDate);
    	 
    	//qna process 셋팅
    	QnaProcess qnaProcess = qnaForm.getQuestionProcess();
    	qnaProcess.setProcessSeq(0);
    	qnaProcess.setEmail(qna.getCustomerEmail());
		qnaProcess.setMailActionResult(ApiPublic.ACTION_RESULT_INITIAL);
		qnaProcess.setMobileActionResult(ApiPublic.ACTION_RESULT_INITIAL);
		qnaProcess.setWebActionResult(ApiPublic.ACTION_RESULT_INITIAL);
		qnaProcess.setCreatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
		qnaProcess.setCreatedDate(createdDate);
		qnaProcess.setUpdatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
		qnaProcess.setUpdatedDate(createdDate);

		//qnaContents
    	QnaContents qnaContents = new QnaContents();
    	qnaContents.setProcessSeq(0);
    	qnaContents.setContentsSeq(0);
    	qnaContents.setContentsType("Q");
    	qnaContents.setContents(qnaForm.getQuestionContents());
    	qnaContents.setCreatedDate(createdDate);
    	
    	ArrayList attachList = null;
    	if (qnaForm.getQuestionAttachList() != null && qnaForm.getQuestionAttachList().size() > 0)
    	{
    		//attachList = (ArrayList) ((LazyList)qnaForm.getQuestionAttachList()).subList(0, qnaForm.getQuestionAttachList().size()-1);
    		attachList = (ArrayList)qnaForm.getQuestionAttachList();
    		Attach attach = null;
    		for (Iterator it = attachList.iterator(); it.hasNext();)
    		{
    			attach = ((Attach)it.next());
    			attach.setCreatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
    			attach.setCreatedDate(createdDate);
    		}
    	}
    	 
    	String qnaId = insertQna(qna, qnaBoard, qnaProcess, qnaContents, attachList);
    	 
    	//룰을 호출할것인가?
    	RuleCaller.callQnaRouteRule();
    	
    	return qnaId;
    }
    
	/**
     * 이메일상담 등록(모바일웹용)
     * @param qnaForm
     * @return
     */
    public String insertQnaByMobileWeb(QnaWebForm qnaWebForm)
    {
    	String createdDate = DateUtil.getCurrDateTimeStamp();
    	//Qna 중 파라메터로 받는 값들
    	//파라메터로 받지 않은 기본값을 셋팅한다.  
    	Qna qna = (Qna)qnaWebForm;
    	 
    	qna.setAccountId(StringUtil.defaultIfEmpty(qna.getAccountId(), ApiPublic.ACCOUNT_ID_NO_AGENT));
    	qna.setAnswerChannelId(StringUtil.defaultIfEmpty(qna.getAnswerChannelId(), ApiPublic.CHANNEL_ID_NOT_RESPONSE));
    	 
    	//제목이 안넘오어면 내용에서 앞 부분을 짤라서 제목으로 구성한다.
    	qna.setSpamFlag(StringUtil.defaultIfEmpty(qna.getSpamFlag(), ApiPublic.FLAG_I));
    	qna.setCreatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
    	qna.setCreatedDate(createdDate);
    	qna.setUpdatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
    	qna.setUpdatedDate(createdDate);
    	 
    	//qna board 셋팅
    	QnaBoard qnaBoard = qnaWebForm.getQnaBoard();
    	qnaBoard.setCreatedDate(createdDate);
    	qnaBoard.setUpdatedDate(createdDate);
    	 
    	//qna process 셋팅
    	QnaProcess qnaProcess = qnaWebForm.getQuestionProcess();
    	qnaProcess.setProcessSeq(0);
    	qnaProcess.setEmail(qna.getCustomerEmail());
		qnaProcess.setMailActionResult(ApiPublic.ACTION_RESULT_INITIAL);
		qnaProcess.setMobileActionResult(ApiPublic.ACTION_RESULT_INITIAL);
		qnaProcess.setWebActionResult(ApiPublic.ACTION_RESULT_INITIAL);
		qnaProcess.setCreatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
		qnaProcess.setCreatedDate(createdDate);
		qnaProcess.setUpdatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
		qnaProcess.setUpdatedDate(createdDate);

		//qnaContents
    	QnaContents qnaContents = new QnaContents();
    	qnaContents.setProcessSeq(0);
    	qnaContents.setContentsSeq(0);
    	qnaContents.setContentsType("Q");
    	qnaContents.setContents(qnaWebForm.getQuestionContents());
    	qnaContents.setCreatedDate(createdDate);
    	
    	ArrayList attachList = null;
    	if (qnaWebForm.getQuestionAttachList() != null && qnaWebForm.getQuestionAttachList().size() > 0)
    	{
    		//attachList = (ArrayList) ((LazyList)qnaForm.getQuestionAttachList()).subList(0, qnaForm.getQuestionAttachList().size()-1);
    		attachList = (ArrayList)qnaWebForm.getQuestionAttachList();
    		Attach attach = null;
    		for (Iterator it = attachList.iterator(); it.hasNext();)
    		{
    			attach = ((Attach)it.next());
    			attach.setCreatedBy(ApiPublic.AGENT_SYSTEM_CUSTOMER);
    			attach.setCreatedDate(createdDate);
    		}
    	}
    	 
    	String qnaId = insertQna(qna, qnaBoard, qnaProcess, qnaContents, attachList);
    	 
    	//룰을 호출할것인가?
    	RuleCaller.callQnaRouteRule();
    	
    	return qnaId;
    }
    
    /**
     * 주어진 QnA 아이디에 해당하는 QnA를 삭제한다.
     * @param qnaId 삭제한 QnA 아이디
     * @return 삭제 성공 실패 여부
     */
    public Integer deleteQna(QnaBoardView qnaBoardView)
    {
    	Integer iret = 0;
    	
        try
        {
        	//삭제함수이므로 deleteFlag 는 고정
        	qnaBoardView.setDeleteFlag(ApiPublic.FLAG_Y);
            sqlMap.startTransaction();
            iret = sqlMap.update("Qna.updateDeleteFlagByPK", qnaBoardView);
            sqlMap.commitTransaction();
        }
        catch (Exception e)
        {
        	logger.error(e.getMessage());
        }
        finally
        {
            try
            {
                sqlMap.endTransaction();
            }
            catch(SQLException e)
            {
                logger.error(e.getMessage());
            }
        }
        return iret;
    }
    
    /**
     * <pre>
     * 읽지 않은 메일 건수 체크
     * </pre>.
     */
    public int selectQnaNotReadCount(QnaBoardView qnaBoard)
    {
        int iRet = 0;
        try
        {
            Integer intObj = (Integer) sqlMap.queryForObject("Qna.selectNotReadCountBySmartApp", qnaBoard.getCustomerId());
            iRet = intObj.intValue(); 
        }
        catch (Exception e)
        {
            logger.error(e.getMessage());
        }
        return iRet;
    }
    
    /**
     * <pre>
     * 나의 상담 현황 건수 체크(총건수, 답변건)
     * </pre>.
     */
    public Object selectMyQnaCount(QnaBoardView qnaBoard)
    {
    	JSONObject json = new JSONObject();
        try
        {
        	List listRet = (List) sqlMap.queryForList("Qna.selectMyQnaCount", qnaBoard);
        	if(listRet != null && listRet.size() > 0)
        	{
        		CaseInsensitiveMap map = (CaseInsensitiveMap)listRet.get(0);
        		
        		int iTotalCnt = Integer.parseInt(map.get("TOTAL_CNT")+"");
        		int iAnswerCnt = Integer.parseInt(map.get("ANSWER_CNT")+"");
        		
        		ArrayList arrList = new ArrayList();
        		
        		Map hMap = new HashMap();
        		hMap.put("total_cnt", iTotalCnt);
        		hMap.put("answer_cnt", iAnswerCnt);
        		arrList.add(hMap);

        		json.put("LIST", arrList);
        	}
        }
        catch (Exception e)
        {
            logger.error(e.getMessage());
        }
        return json;
    }
}